import { Module } from 'vuex'
import http from '@/http/index'
import { api } from '@/http/api'
import GlobalDataProps from '../types'
import { NewsCenter, NoticeModel, NoticeEditStatusAllModel } from './types'
import { PagingModel } from '@/store/baseTypes'

const newsCenter: Module<NewsCenter, GlobalDataProps> = {
  namespaced: true,
  state: {
    sysNotice: undefined,
    activeNotice: undefined,
    customNotice: undefined
  },
  getters: {},
  mutations: {},
  actions: {
    // 获取未读公告或通知
    handleGetNoReadNotice: async (
      { commit }: any,
      params: {
        type: 1 | 2 // 1通知 2 公告
        status?: 0 | 1 // 0未读 1已读
        noticeType?: 1 | 2 | 3 | 4 | 5 // 1系统消息, 2运单消息, 3客服消息, 4活动消息, 4 报警消息
      }
    ): Promise<PagingModel<NoticeModel>> => {
      let finalResult: any
      try {
        const result = await http({
          method: 'get',
          params,
          url: api.getNoReadNotice
        })
        if (result) {
          let rows: any = []
          if (result && result.length > 0) {
            rows = result.map((item: NoticeModel) => {
              item.sysNoticeEntity = item.sysNoticeEntity || {}
              return item
            })
          }
          finalResult = rows
        }
      } catch (e) {
        console.log(`ERROR FROM handleGetNotice:${e}`)
      }
      return finalResult
    },
    // 获取公告或通知
    handleGetNotice: async (
      { commit }: any,
      params: {
        type: 1 | 2 // 1通知 2 公告
        status?: 0 | 1 // 0未读 1已读
        noticeType?: 1 | 2 | 3 | 4 | 5 // 1系统消息, 2运单消息, 3客服消息, 4活动消息, 5 报警消息
      }
    ): Promise<PagingModel<NoticeModel>> => {
      let finalResult: any = {}
      try {
        const result = await http({
          method: 'get',
          params,
          url: api.getNotice
        })
        if (result) {
          let rows: any = []
          console.log(result.rows, 'result.rows')
          if (result.rows) {
            rows = result.rows.map((item: NoticeModel) => {
              item.sysNoticeEntity = item.sysNoticeEntity || {}
              return item
            })
          }

          finalResult = {
            pageNo: result.pageNo,
            pageSize: result.pageSize,
            rows,
            totalPage: result.totalPage,
            totalRows: result.totalRows
          }
        }
      } catch (e) {
        // console.log(`ERROR FROM handleGetNotice:${e}`)
      }
      return finalResult
    },
    // 通知或公告一键修改状态
    handleSysNoticeReadingByType: async ({ commit }: any, data: NoticeEditStatusAllModel): Promise<boolean> => {
      let finalResult = false
      try {
        data = Object.assign(data, { system: 1 })
        await http({
          url: api.sysNoticeReadingByType,
          method: 'post',
          data
        })
        finalResult = true
      } catch (e) {
        console.log(`ERROR FROM handleSysNoticeReadingByType:${e}`)
      }
      return finalResult
    }
  }
}
export default newsCenter
